<!-- 国家地区增改弹窗 -->

<style lang="scss" scoped>
.el-form {
  .el-form-item {
    margin: 15px 0;
  }

  .hjd-drawer__footer {
    margin-top: 50px;
  }
}
</style>

<template>
  <el-drawer
    ref="drawer"
    custom-class="hjd-drawer"
    :title="`${status === 'create' ? '新增' : '编辑'}角色管理`"
    :visible.sync="showDialog"
    :wrapper-closable="true"
    @close="$emit('update:visible', false)"
  >
    <div class="hjd-drawer__content">
      <el-form
        ref="dataForm"
        :model="form"
        label-width="100px"
        style=" margin-left:20px;margin-right:20px;"
      >
        <div class="hjd-drawer__content_tree">

          <el-form-item label="角色名称">
            <el-input v-model="form.name" />
          </el-form-item>

          <el-form-item
            label="是否启用"
            prop="status"
          >
            <el-switch v-model="form.status" />
          </el-form-item>
        </div>
        <div class="hjd-drawer__footer">
          <el-button @click="showDialog = false">
            取消
          </el-button>
          <el-button
            type="primary"
            @click="submit"
          >
            确定
          </el-button>
        </div>

      </el-form>
    </div>
  </el-drawer>
</template>

<script>

import _ from 'lodash'

import { handleAdd, handleEdit } from '@/api/system/auth/role'

export default {
  name: 'UpdateRoleDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    status: {
      type: String,
      default: 'new'
    },
    data: {
      type: Object,
      default: () => ({})
    },

    parent: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      showDialog: this.visible,

      beforeData: {},

      /**
       * 表单内容
       */
      form: {
        role_id: '',
        name: '',
        status: 1
      }
    }
  },

  created() {
    this.beforeData = _.cloneDeep(this.data)
    if (this.status === 'update') {
      this.form = _.cloneDeep(this.data)
    }
  },

  methods: {
    submit() {
      // 数据没改动 直接关闭弹窗
      if (_.isEqual(this.form, this.beforeData)) {
        this.showDialog = false
        return
      }

      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // 是否是创建
          const isCreate = this.status === 'create'

          // 请求数据
          const queryData = {
            name: this.form.name,
            status: this.form.status
          }

          // 修改时传 ID
          if (!isCreate) queryData['role_id'] = this.form.role_id

          // 请求接口
          const request = isCreate ? handleAdd : handleEdit
          request(queryData).then(() => {
            this.data.name = this.form.name
            this.data.status = this.form.status
            this.showDialog = false
            this.$notify.success(isCreate ? '创建成功' : '修改成功')
            // 刷新列表
            // this.$emit('reload')
          })
        }
      })
    }
  }
}
</script>
